package com.sara.controller;

import com.sara.entity.Permission;
import com.sara.entity.Role;
import com.sara.exception.ServiceException;
import com.sara.service.PermissionService;
import com.sara.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;


@Controller
@RequestMapping("/manage/role")
public class RoleController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    @GetMapping
    public String listPage(Model model) {
        List<Role> roleList = roleService.findAllRole();
        model.addAttribute("roleList",roleList);
        return "manage/role/list";
    }


    @GetMapping("/add")
    public String addPage(Model model){
        List<Permission> permissionList = permissionService.findAllPermission();
        model.addAttribute("permissionList",permissionList);
        return "manage/role/add";
    }

    @PostMapping("/add")
    public String add(Role role, Integer[] permissionId, RedirectAttributes attributes){
        roleService.saveRole(role,permissionId);
        attributes.addFlashAttribute("message","新增成功");
        return"redirect:/manage/role";
    }

    @GetMapping("/edit/{id:\\d+}")
    public String editPage(@PathVariable Integer id, Model model){
        Role role = roleService.findRoleByRoleId(id);
        List<Permission> permissionList = permissionService.findAllPermission();
        for(Permission permission : permissionList){
            for(Permission per : role.getPermissionList()){
                if(permission.getId() == per.getId()){
                    permission.setIsChecked("checked");
                }
            }
        }

        model.addAttribute("permissionList", permissionList);
        model.addAttribute("role", role);
        return "manage/role/edit";
    }

    @PostMapping("/edit")
    public String edit(Role role, Integer[] permissionId, RedirectAttributes attributes){
        roleService.edit(role,permissionId);
        attributes.addFlashAttribute("message", "修改成功!");
        return "redirect:/manage/role";
    }


    @GetMapping("/delete/{id:\\d+}")
    public String delete(@PathVariable Integer id, RedirectAttributes attributes){

        try {
            roleService.deleteByRoleId(id);
            attributes.addFlashAttribute("message", "删除成功!");
        }catch (ServiceException e){
            attributes.addFlashAttribute("message", e.getMessage());
        }

        return "redirect:/manage/role";

    }

}